package com.gpscookie.vocabularystory;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

public class EntryScreen extends TabActivity {
	private String book;
	private String entry;
	private ArrayList<Story> stories;
	private int size = Utils.INSTANCE.pageSize;
	private int offset = 0;
	private ListView list;
	private StoryListAdapter adapter;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        stories = new ArrayList<Story>();
        
        TabHost th = getTabHost();
        LayoutInflater.from(this).inflate(R.layout.entry, th.getTabContentView(), true);
        th.addTab(th.newTabSpec(getString(R.string.basic))
                .setIndicator(getString(R.string.basic))
                .setContent(R.id.tabbasic));
        th.addTab(th.newTabSpec(getString(R.string.note))
                .setIndicator(getString(R.string.note))
                .setContent(R.id.tabstory));
        th.addTab(th.newTabSpec(getString(R.string.reference))
                .setIndicator(getString(R.string.reference))
                .setContent(R.id.tabweb));
        
        TextView txtEntry = (TextView)findViewById(R.id.txtentry);
        TextView txtDesc = (TextView)findViewById(R.id.txtdesc);
        TextView txtShortdesc = (TextView)findViewById(R.id.txtshortdesc);
        TextView txtVoice = (TextView)findViewById(R.id.txtvoice);
        WebView web = (WebView)findViewById(R.id.weburl);
        Intent it = this.getIntent();
        entry = it.getStringExtra("entry");
		txtEntry.setText(entry);
		txtDesc.setText(it.getStringExtra("desc"));
		book = it.getStringExtra("key");
		// it.getIntExtra("level", 0);
		txtShortdesc.setText(it.getStringExtra("shortdesc"));
		
        web.setWebViewClient(new WebViewClient() {
	    	@Override
	    	public boolean shouldOverrideUrlLoading (WebView view, String lurl) {
	    		Log.i("EntryScreen:shouldOverrideUrlLoading():", lurl);
	    		return false;
	    	}
        });
		
		web.loadUrl(it.getStringExtra("url"));
		txtVoice.setText(String.format("[%s]", it.getStringExtra("voice")));        
		
		list = (ListView)findViewById(R.id.stroylist);
		adapter = new StoryListAdapter(this);
		list.setAdapter(adapter);
		
		Button btnAddStory = (Button)findViewById(R.id.btnadd);
		btnAddStory.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				Intent it = new Intent(EntryScreen.this, AddStoryScreen.class);
				it.putExtra("book", book);
				it.putExtra("entry", entry);
				startActivity(it);
			}			
		});
		
		new StoryDownloadTask().execute(null);
    }	
    
    private class StoryListAdapter extends BaseAdapter {
    	Context context;
		private LayoutInflater inflater;

		public StoryListAdapter(Context cx) {
			context = cx;
			inflater = LayoutInflater.from(context);
		}

		public int getCount() {
			return stories.size();
		}

		public Object getItem(int arg0) {
			return stories.get(arg0);
		}

		public long getItemId(int arg0) {
			return arg0;
		}

		public View getView(int pos, View v, ViewGroup arg2) {
			if (v==null) {
				v = inflater.inflate(R.layout.storylistitem, null);
			}
			TextView txtTime = (TextView) v.findViewById(R.id.txttimestamp);
			TextView txtAuthor = (TextView) v.findViewById(R.id.txtauthor);
			TextView txtStory = (TextView) v.findViewById(R.id.txtstory);
			txtTime.setText(stories.get(pos).getTimestamp());
			txtAuthor.setText(stories.get(pos).getAuthor());
			txtStory.setText(stories.get(pos).getStory());
			return v;
		}
    	
    }
    
    private class StoryDownloadTask extends AsyncTask<Void, Void, Boolean> {

		@Override
		protected Boolean doInBackground(Void... arg0) {
			boolean rtn = false;
			SimpleDBHelper db = new SimpleDBHelper(EntryScreen.this);
			JSONObject result = db.getJSON(Utils.INSTANCE.composeStoryListURL(book, entry, size, offset), true);
			if (Utils.INSTANCE.getJSONResultError(result)==0) {
				JSONArray array = Utils.INSTANCE.getJSONResultArray(result);
				if (array==null) {
					rtn = false;
				} else {
					for (int i=0; i<array.length(); i++) {
						try { 
							JSONObject row = array.getJSONObject(i);
							String url = row.getString("url");
							String story = row.getString("story");
							String timestamp = row.getString("timestamp");		
							int popularity = row.getInt("popularity");
							String author = row.getString("author");
							Story obj = new Story();
							obj.setUrl(url);
							obj.setStory(story);
							obj.setTimestamp(timestamp);
							obj.setPopularity(popularity);
							obj.setAuthor(author);
							stories.add(obj);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}	
					}
					rtn = true;
				}
			} else {
				rtn = false;
			}
			db.close();
			return rtn;
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			Log.i("EntryScreen:onPostExecute():", "return "+result);
			if (result) {
				adapter.notifyDataSetChanged();		
			} else {
				Toast.makeText(EntryScreen.this, 
						getString(R.string.networkerror),
						Toast.LENGTH_LONG).show();				
			}
		}
    }

}
